package com.my.blog.website.controller;

import com.github.pagehelper.PageInfo;
import com.my.blog.website.constant.WebConst;
import com.my.blog.website.modal.Bo.QiniuResponse;
import com.my.blog.website.modal.Vo.*;
import com.my.blog.website.modal.from.QuestionWriteForm;
import com.my.blog.website.service.IQuestionCategoryService;
import com.my.blog.website.service.IQuestionCommentService;
import com.my.blog.website.service.IQuestionService;
import com.my.blog.website.service.UploadService;
import com.my.blog.website.utils.UUID;
import com.qiniu.http.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * @Description 问答控制器
 * @ClassName QuestionController
 * @Author gyh
 * @date 2020.08.03 13:09
 */
@Controller
@Slf4j
public class QuestionController extends BaseController {

    @Resource
    IQuestionCategoryService questionCategoryService;

    @Resource
    private IQuestionService questionService;

    @Resource
    IQuestionCommentService commentService;

    @Resource
    private UploadService uploadService;


    /**
     * @MethodName: questionList
     * @Description: 问答列表
     * @Param: [model]
     * @Return: java.lang.String
     * @Author: gyh
     * @Date: 2020-08-03 13:22
     **/
    @GetMapping(value = "question/{p}")
    public String questionList(HttpServletRequest request, @PathVariable int p,
                               @RequestParam(value = "limit", defaultValue = "15") int limit) {
        p = p < 0 || p > WebConst.MAX_PAGE ? 1 : p;
        PageInfo<QuestionVo> questions = questionService.getQuestions(p, limit);
        List<QuestionVo> questionList = questions.getList();
        request.setAttribute("questionList", questionList);
        request.setAttribute("pageParam", questions);
        if (p > 1) {
            this.title(request, "第" + p + "页");
        }
        // 分类信息
        List<QuestionCategoryVo> categoryList = questionCategoryService.getQuestionlist(null);
        request.setAttribute("categoryList", categoryList);
        this.keywords(request);
        return this.render("/question/list");
    }

    /**
     * @Author: gyh
     * @Description: 发布问题
     * @DateTime: 2020/9/18 1:08
     * @Params: [model]
     * @Return java.lang.String
     */
    @GetMapping("/question/write")
    public String toWrite(Model model) {
        List<QuestionCategoryVo> categoryList = questionCategoryService.getQuestionlist(null);
        model.addAttribute("categoryList", categoryList);
        return this.render("/question/write");
    }

    /**
     * @Author: gyh
     * @Description: 阅读问题
     * @DateTime: 2020/9/21 23:53
     * @Params: [qid, model]
     * @Return java.lang.String
     */
    @GetMapping("/question/read/{qid}")
    public String read(@PathVariable("qid") String qid, Model model) {
        QuestionVo question = questionService.getQuestionByQid(qid);
        // todo: redis缓存. 防止阅读重复
        question.setViews(question.getViews() + 1);
        questionService.update(question);
        model.addAttribute("question", question);
        // todo： 查询评论.
        List<QuestionCommentsVo> commentsVoList = commentService.listComment(qid);
        model.addAttribute("commentList", commentsVoList);
        return this.render("question/read");
    }

    @PostMapping("/question/comment/{qid}")
    public String post(QuestionCommentsVo comment, @PathVariable String qid) {
        comment.setId(UUID.UU32());
        comment.setCreateTime(new Date());
        if (comment.getParentComment().getId() != null) {
            comment.setParentCommentId(comment.getParentComment().getId());
        }
        commentService.saveComment(comment);
        return "redirect:/question/read/" + qid;
    }

    /**
     * @Author: gyh
     * @Description: 问答发布
     * @DateTime: 2020/9/20 23:44
     * @Params: [questionWriteForm]
     * @Return java.lang.String
     */
    @PostMapping("/question/write")
    @ResponseBody
    public synchronized R write(QuestionWriteForm questionWriteForm) {
        // 构建问题对象
        QuestionVo question = new QuestionVo();
        question.setQid(UUID.UU32());
        question.setTitle(questionWriteForm.getTitle());
        question.setContent(questionWriteForm.getContent());
        question.setStatus(0);
        question.setSort(0);
        question.setViews(0);
        question.setAuthorId(questionWriteForm.getAuthorId());
        question.setAuthorName(questionWriteForm.getAuthorName());
        question.setAuthorAvatar(questionWriteForm.getAuthorAvatar());
        QuestionCategoryVo category = questionCategoryService.getById(questionWriteForm.getCategoryId());
        question.setCategoryId(questionWriteForm.getCategoryId());
        question.setCategoryName(category.getCategory());
        question.setGmtCreate(new Timestamp(System.currentTimeMillis()));
        question.setGmtUpdate(new Timestamp(System.currentTimeMillis()));
        // 存储对象
        questionService.save(question);
        return R.ok("发布成功");
    }

    @PostMapping(value = "/question/upload_qiniu")
    @ResponseBody
    public R upload_qiniu(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file)
            throws IOException {
        if (file.isEmpty()) {
            return R.error(HttpStatus.SC_NOT_FOUND, "项目图片不能为空");
        }
        try {
            Response fileResponse = uploadService.upload(file);
            QiniuResponse info = fileResponse.jsonToObject(QiniuResponse.class);
            //修改七牛云返回的url没有http://
            return R.ok("上传图片成功").put("url", "http://" + info.getUrl());
        } catch (IOException e) {
            e.printStackTrace();
            //上传图片失败
            return R.error(HttpStatus.SC_BAD_REQUEST, "上传图片失败");
        }
    }
}
